import requests
from kgcar.spider.settings import DEFAULT_REQUEST_HEADERS
from kgcar.spider.settings import EXECUTABLE_PATH, HEADLESS
from selenium import webdriver
import platform


class PageRenderer(object):
    def __init__(self):
        self.timeout = 30
        self.executable_path = EXECUTABLE_PATH
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--disable-gpu")
        if HEADLESS:
            chrome_options.add_argument('--headless')
        # 去除 --ingor
        chrome_options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # chrome_options.add_argument('--disable-gpu')
        if platform.system() == 'Windows':
            self.browser = webdriver.Chrome(executable_path=self.executable_path, chrome_options=chrome_options)
        else:
            chrome_options.add_argument('no-sandbox')  # 针对linux root用户
            self.browser = webdriver.Chrome(chrome_options=chrome_options)

    def render_page(self, url):
        self.browser.get(url)
        return self.browser.page_source

    def load_page(self, url):
        self.browser.get(url)

    def click_xpath(self, xpath):
        self.browser.find_element_by_xpath(xpath).click()


def get_page(url):
    s = requests.session()
    response = s.get(url=url, headers=DEFAULT_REQUEST_HEADERS, allow_redirects=False)
    response.encoding = 'gbk'
    html = response.text
    return html